fix(cluster-labels): single-flight guard for vocab cache builds#274
Merged
Conversation
Concurrent /cluster_labels and /image_label requests both dispatch get_or_build_vocab_embeddings through asyncio.to_thread, so on a cold cache every caller would re-load the encoder and re-encode the full vocabulary before the first writer's atomic rename landed. Add a per-encoder threading.Lock with a re-check inside the lock so the second waiter picks up the first builder's output instead. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
/cluster_labelsand/image_labelrequests both dispatchget_or_build_vocab_embeddingsthroughasyncio.to_thread. Every caller sawcache_pathmissing, loaded the encoder, and re-encoded the full vocabulary before the first writer's atomic.tmp→ rename landed — observed as 5+ duplicate "Building vocab embeddings cache at …" lines per cold start.threading.Lockregistry around the build path incluster_labels.py, with a re-check of_read_cached_vocabinside the lock so the second waiter picks up the first builder's atomic rename instead of redundantly re-encoding.Test plan
pytest tests/backend/test_cluster_labels.py— 38/38 pass, including a newtest_concurrent_builds_are_serializedthat spawns 4 threads against a gated fake encoder and assertsencode_calls == 1.ruff check photomap/backend/cluster_labels.py tests/backend/test_cluster_labels.pyclean.~/.cache/photomap/cluster_vocab/and trigger several concurrent slide-drawer opens; log should show one "Building vocab embeddings cache" line followed by one "Vocab embeddings cached".🤖 Generated with Claude Code